package logic

import (
	"context"
	"encoding/json"

	"diff.wang/asynqsrv/clientrpc/internal/svc"
	"diff.wang/asynqsrv/clientrpc/pb"
	"diff.wang/asynqsrv/common"
	"diff.wang/asynqsrv/common/tool"

	"github.com/hibiken/asynq"
	"github.com/zeromicro/go-zero/core/logx"
)

type CloseLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCloseLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CloseLogic {
	return &CloseLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

//  关闭订单 延时
func (l *CloseLogic) Close(in *pb.CloseReq) (*pb.CloseResp, error) {
	// todo: add your logic here and delete this line
	payload, err := json.Marshal(common.CloseOrderPayload{
		OrderId: int(in.OrderId),
	})
	if err != nil {
		return nil, err
	}
	task := asynq.NewTask(common.DeferCloseOrder, payload)
	// 延时处理
	t, err := tool.GetGoTime(in.DateTime)
	if err != nil {
		return nil, err
	}
	ti, err := l.svcCtx.AsynqClient.Enqueue(task, asynq.MaxRetry(int(in.Retry)), asynq.ProcessAt(*t))
	if err != nil {
		return nil, err
	}
	logx.Info("push close queue success, %+v", ti)

	return &pb.CloseResp{
		Tag: true,
	}, nil
}
